package net.lgpage.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;


public class DownloadThread extends Thread {

	String url;
	String dir;
	String filename;

	@Override
	public void run() {
		try {
			download(url, dir, filename);
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.run();
	}

	public void setOnDownloadingListener(OnDownloadingListener onDownloadingListener) {
		this.onDownloadingListener = onDownloadingListener;
	}

	public String getFileName(HttpURLConnection conn) {
		String fn = null;
		try {
			fn = URLDecoder.decode(conn.getURL().toString(), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			return fn.substring(fn.lastIndexOf("/") + 1);
		} catch (Exception e) {
			return null;
		}
	}

	public DownloadThread(String url, String dir, String filename) {
		super();
		this.url = url;
		this.dir = dir;
		this.filename = filename;
	}

	OnDownloadingListener onDownloadingListener;

	boolean stopflag = false;

	private void download(String url, String dir, String filename) {
		long position = 0;
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestMethod("GET");
		} catch (Exception e) {
			e.printStackTrace();
		}
		conn.setConnectTimeout(5000);
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
		long length = conn.getContentLength();
		if (filename == null) {
			filename = getFileName(conn);
		}
		File fdir = new File(dir);
		if(!fdir.exists())fdir.mkdirs();
		String path = dir + filename;
		RandomAccessFile file = null;
		try {
			file = new RandomAccessFile(path, "rwd");
			file.setLength(length);
			file.seek(position);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		long currentPostion = position;
		InputStream is = null;
		try {
			is = conn.getInputStream();
			int len;
			byte[] buffer = new byte[1024];
			while ((len = is.read(buffer)) != -1) {
				if (stopflag) {
					is.close();
					if (onDownloadingListener != null) {
						onDownloadingListener.onCancel();
					}
					file.close();
					return;
				}
				file.write(buffer, 0, len);
				currentPostion += len;
				if (onDownloadingListener != null) {
					onDownloadingListener.onDownloading(currentPostion, length);
				}
			}
			is.close();
			if (onDownloadingListener != null) {
				onDownloadingListener.onFinish(new File(path));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				file.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/*
	 * private InputStream downloadPartFile(URL url, long startposition, long
	 * endpositon) throws IOException { HttpURLConnection conn = null; conn =
	 * (HttpURLConnection) url.openConnection();
	 * conn.setRequestProperty("Range", "bytes=" + startposition + "-" +
	 * endpositon); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000);
	 * conn.setRequestProperty("User-Agent",
	 * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); InputStream
	 * is = conn.getInputStream(); return is; }
	 * 
	 * public HttpURLConnection requestUrl(URL url) throws IOException {
	 * HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	 * conn.setRequestMethod("GET"); conn.setConnectTimeout(5000);
	 * conn.setRequestProperty("User-Agent",
	 * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); int code =
	 * conn.getResponseCode(); if (code == 200) { return conn; } else { throw
	 * new IOException("网络位置问题"); } }
	 */

	public void stopDownload() {
		stopflag = true;
	}
	public static interface OnDownloadingListener {
		public void onDownloading(long progress, long maxlength);

		public void onFinish(File file);

		public void onCancel();
	}

}
